package com.tbit.main.controller;

import com.tbit.common.enums.OperaPswEnum;
import com.tbit.common.group.DefaultGroupA;
import com.tbit.main.constant.OperaPswConstant;
import com.tbit.main.constant.UserConstant;
import com.tbit.main.controller.interceptor.LoginUserContextHolder;
import com.tbit.main.dao.core.AccountDao;
import com.tbit.main.dao.core.UserDao;
import com.tbit.main.exception.BaseException;
import com.tbit.main.pojo.AccountUser;
import com.tbit.main.pojo.Coupon;
import com.tbit.main.pojo.Result;
import com.tbit.main.pojo.User;
import com.tbit.main.service.CouponService;
import com.tbit.main.service.OperaPswService;
import com.tbit.main.service.PurviewService;
import com.tbit.main.util.Assert;
import com.tbit.manager.api.CouponApi;
import com.tbit.manager.api.dto.CouponUserDTO;
import com.tbit.manager.api.dto.PackageDelayDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.NotNull;
import java.util.List;
import java.util.Objects;

/**
 * 优惠券
 */
@Validated
@RestController
@RequestMapping(value = "/coupon")
public class CouponController {

    @Autowired
    private CouponApi couponApi;
    @Autowired
    private PurviewService purviewService;
    @Autowired
    private CouponService couponService;
    @Autowired
    private UserDao userDao;
    @Autowired
    private AccountDao accountDao;
    @Autowired
    private OperaPswService operaPswService;

    /**
     * 查询用户优惠券
     *
     * @param userId     用户ID
     * @param accountId  区域id
     * @param pageSize   条数
     * @param pageNum 页码
     * @return Result<List<CouponUserDTO>>
     */
    @GetMapping("/getByUserIdPage")
    public Result<List<CouponUserDTO>> getByUserIdPage(@RequestParam("userId") @NotNull(message = "用户ID不能为空") Integer userId,
                                                       @RequestParam("accountId") @NotNull(message = "accountId不能为空") Integer accountId,
                                                       @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize,
                                                       @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum) {
        List<CouponUserDTO> couponUserDTOList = couponApi.getByUserIdPage(userId, accountId, pageSize, pageNum);
        return Result.success(couponUserDTOList);
    }

    /**
     * 获取代理商所有可以优惠券
     *
     * @param accountId  区域id
     * @return List<CouponUserDTO>
     */
    @GetMapping("/getCouponIsVail")
    public Result<List<CouponUserDTO>> getCouponIsVail(Integer accountId) {
        // 获取用户信息
        AccountUser loginUser = LoginUserContextHolder.getLoginUser();
        if (!UserConstant.ACCOUNT_AGENT.equals(loginUser.getAccountUserType())) {
            Assert.notNull(accountId, "System.noAgent");
        } else {
            accountId = loginUser.getAccountId();
        }
        if (!purviewService.purviewCheck(loginUser.getAccountId(), accountId)) {
            throw new BaseException("System.noPower");
        }
        List<CouponUserDTO> couponUserDTOList = couponApi.getCouponIsVail(accountId);
        return Result.success(couponUserDTOList);
    }

    /**
     * 批量赠送用户优惠券
     *
     * @param couponUserDTO .
     * @return Result<String>
     */
    @GetMapping("/addBatch")
    public Result<String> addBatch(@Validated(DefaultGroupA.class) CouponUserDTO couponUserDTO) {

        AccountUser loginUser = LoginUserContextHolder.getLoginUser();
        couponUserDTO.setLoginUserName(loginUser.getName());
        couponUserDTO.setAccountId(loginUser.getAccountId());

        Coupon couponInDb = couponService.getBycouponId(couponUserDTO.getCouponId());
        if (couponInDb == null) {
            throw new BaseException("coupon.not.exist");
        }
        User user = userDao.getByUserId(couponUserDTO.getUserId());
        if (Objects.isNull(user)) {
            throw new BaseException("user.not.exist");
        }
        Integer brandId = accountDao.getByAccount(couponInDb.getAccountId());
        if (!brandId.equals(user.getAccountId())) {
            throw new BaseException("当前优惠劵所在品牌下不存在此用户");
        }

        couponApi.addBatch(couponUserDTO);

        return Result.success();
    }

    /**
     * 延长优惠券到期时间
     *
     * @param delayDTO .
     */
    @GetMapping("/modifyExpireTime")
    public Result<String> modifyExpireTime(@Validated(DefaultGroupA.class) PackageDelayDTO delayDTO) {
        /**操作密码校验 兼容5.0.0之前版本 常量校验不通过时，再调接口校验*/
        if (!OperaPswConstant.USER_OPERA_UPDATE_MONEY.equals(delayDTO.getPwd())) {
            operaPswService.checkOperaPsw(LoginUserContextHolder.getLoginUser(), OperaPswEnum.OPERA_PSW_COUPONS_CONFIG.getModule(),
                    delayDTO.getPwd());
        }
        couponApi.modifyExpireTime(delayDTO);
        return Result.success();
    }

    /**
     * 根据用户id和用户优惠券id置为失效
     *
     * @param allFailures  是否全部失效
     * @param couponUserId 根据用户优惠券id置为失效
     * @param userId       根据用户将优惠券全部置为失效
     */
    @GetMapping("/userCouponEdit")
    public Result<String> userCouponEdit(@NotNull Boolean allFailures, Integer couponUserId, Integer userId) {
        if (allFailures && userId == null) {
            Assert.notNull(userId, "ver.userId.notNull");
        }
        if (!allFailures && couponUserId == null) {
            Assert.notNull(couponUserId, "ver.couponUserId.notNull");
        }
        if (allFailures) {
            couponApi.userCouponEdit(null, userId);
        } else {
            couponApi.userCouponEdit(couponUserId, null);
        }
        return Result.success();
    }
}
